package com.yueke.gemini.httpclient;

import static org.junit.Assert.fail;

import org.apache.commons.codec.binary.Base64;
import org.junit.Test;

import Decoder.BASE64Decoder;

import com.alibaba.fastjson.JSONObject;

public class HttpClientUtilTest {

	@Test
	public void testSendHttpPostString() {
		JSONObject obj=new JSONObject();
		obj.put("osFlag", "1");
		String param=encrypAndSignJsp(obj.toJSONString());
		 String responseContent = HttpClientUtil.getInstance()
//				 .sendHttpPost("http://www.baidu.com");
	                .sendHttpPost("http://172.16.6.28:8080/cfsmgmt/CallApiServlet?opName=check_describe&osFlag=3&param="+param+"&userId=DT5566224");
		 String result=decrypAndSignJsp(responseContent);
	        System.out.println("reponse content:" + result);
	}


	public void testSendHttpPostStringString() {
		fail("Not yet implemented");
	}


	public void testSendHttpPostStringMapOfStringString() {
		fail("Not yet implemented");
	}


	public void testSendHttpPostStringMapOfStringStringListOfFile() {
		fail("Not yet implemented");
	}


	public void testSendHttpGet() {
		 String responseContent = HttpClientUtil.getInstance()
	                .sendHttpGet("http://172.16.6.28:8080/cfsmgmt/CallApiServlet?opName=check_describe&osFlag=1");
	        System.out.println("reponse content:" + responseContent);
	}

	public void testSendHttpsGet() {
		fail("Not yet implemented");
	}

	public static String encrypAndSignJsp(String data) {

		String ret = "";
		if (data != null && data.length() > 0) {
			try {
				JSONObject json = JSONObject.parseObject(data);
				String retMsg = json.getString("retMsg");
				if (retMsg != null && retMsg.length() > 0 ) {
					json.put("retMsg", java.net.URLEncoder.encode(retMsg, "UTF-8"));
				}

				//BASE64Encoder encoder = new BASE64Encoder();
//				String str=new String(json.toJSONString().getBytes("UTF-8"),"UTF-8");
				String str=json.toJSONString();
				byte[]b=Base64.encodeBase64URLSafe(str.getBytes("UTF-8"));
				ret=new String(b,"UTF-8");
				//ret = encoder.encode(json.toJSONString().getBytes());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return ret;
	}

	public static String decrypAndSignJsp(String data) {

		if (data != null && data.length() > 0) {

			try {
				BASE64Decoder decorder = new BASE64Decoder();
				//byte[] d = decorder.decodeBuffer(data);
				byte[] d=Base64.decodeBase64(data);
				return new String(d,"UTF-8");

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "";
	}

}
